package com.bank.abmock.config;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XmlRouteConfig extends RouteConfig{
    /*
     * 请求报文规则，由ConfigLoad解析文件得
     * */
    Map<String, Object> requestRules;
    /*
     * 返回报文规则，由ConfigLoad解析文件得
     * */
    Map<String, Object> responseRules;

    @Override
    public Object process(Object request) {
        Map<String, Object> resContent = (Map<String, Object>) request;
        Map<String, Object> rspContent = new HashMap<>();
        //校验请求报文
        for(String key : requestRules.keySet()){
            String rule = (String)requestRules.get(key);
            if("int".equals(rule)){
                Object val = resContent.get(key);
                //判断int类型
                if(val instanceof Integer){
                    System.out.println("key:"+key + "val:" + val + "不符合" + "rule:" + rule);
                }
            }
        }
        //生成返回报文
        for(String key : responseRules.keySet()){
            String rule = (String)responseRules.get(key);
            if("int".equals(rule)){
                resContent.put(key, (int)(Math.random()*1000)); //TODO 换为随机数
            }
            if("string".equals(rule)){
                resContent.put(key, RandomStringUtils.randomAlphanumeric(10)); //TODO换为随机数
            }
            if(StringUtils.startsWithIgnoreCase(rule, "${")){
                //TODO解析${}中的键
                Pattern pattern = Pattern.compile("\\$\\{(.*?)\\}");
                Matcher matcher = pattern.matcher(rule);
                String dateStr = "";
                if (matcher.find()) {
                    dateStr = StringUtils.substringBetween(matcher.group(0), "${", "}");
                    resContent.put(key, dateStr);
                }
            }
        }

        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(JSON.toJSONString(resContent));
            XmlMapper xmlMapper = new XmlMapper();
            String a = xmlMapper.writer().withRootName("root").writeValueAsString(root);
            return a;
        } catch (IOException e) {
            e.printStackTrace();
            return "解析报文失败";
        }
    }

    public Map<String, Object> getRequestRules() {
        return requestRules;
    }

    public void setRequestRules(Map<String, Object> requestRules) {
        this.requestRules = requestRules;
    }

    public Map<String, Object> getResponseRules() {
        return responseRules;
    }

    public void setResponseRules(Map<String, Object> responseRules) {
        this.responseRules = responseRules;
    }
}
